package com.example.work8_1.Service;


import com.example.work8_1.DAO.ProviderRepository;
import com.example.work8_1.Exception.ProviderException;
import com.example.work8_1.entity.Provider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class ProviderService {
    @Autowired
    ProviderRepository pr;

    //增
    public Provider addProvider(Provider p)throws ProviderException
    {
        if(p.getId() != null && pr.findById(p.getId()).isPresent())
        {
            throw new ProviderException("该供应商已存在");
        }
        return pr.saveAndFlush(p);
    }

    //删
    public void deleteProvider(Integer id)throws ProviderException
    {
        if(pr.findById(id) == null)
        {
            throw new ProviderException("该供应商不存在");
        }
        pr.deleteById(id);
    }

    //改
    public void updateProvider(Integer id,Provider p)throws ProviderException
    {
        if(!pr.findById(id).isPresent())
        {
            throw new ProviderException("该供应商不存在");
        }
        pr.saveAndFlush(p);
    }

    //查
    public Provider findProvider(Integer id)
    {
        return pr.findById(id).get();
    }


}
